import TrainDoc from '@/components/TrainDoc';
import {
  addCollection2,
  addFact,
  addGoodArticle,
  addGoodSentence,
} from '@/services/ant-design-pro/brainSpace';
import {
  FilePdfOutlined,
  FileTextOutlined,
  FileUnknownOutlined,
  FileWordOutlined,
  LeftOutlined,
} from '@ant-design/icons';
import { Button, Checkbox, Form, Input, message, Radio, Switch } from 'antd';
import { cloneDeep } from 'lodash';
import { nanoid } from 'nanoid';
import React, { useEffect, useState } from 'react';
import { connect } from 'umi';
const HandleMode: React.FC<any> = (props: any) => {
  const [handleList, setHandleList] = useState<any[]>([]); //操作记录列表
  const [curTabObj, setCurTabObj] = useState<any>(null); //当前tab的对象
  const [trainingSuccess, setTrainingSuccess] = useState<boolean>(false); //是否训练完成
  const [hideBottomBtn, setHideBottomBtn] = useState<boolean>(true); //是否隐藏底部按钮 解析组件显示时出现在底部
  const [content, setContent] = useState<any>(null); // 用户输入的内容 or 上传的文件
  const { TextArea } = Input;
  const { curTab } = props.spaceBot;
  const { cognitionTypes } = props.spaceModel;
  const [curForm] = Form.useForm();
  //公共更新model的方法
  const updateState = (updateObj: any) => {
    props.dispatch({
      type: 'spaceBot/updateStateAsync',
      payload: updateObj,
    });
  };
  useEffect(() => {
    if (cognitionTypes && cognitionTypes.length > 0 && curTab) {
      setTrainingSuccess(false);
      setHandleList(() => []);
      let currentTab = cognitionTypes.find((item: any) => item.name === curTab);
      //当前操作的tab
      setCurTabObj(currentTab);
      //上传提示
      let systemCopyTip = {
        type: 'systemCopy',
        data: `<div class="modeListBox"><div class="modeList autoWidth">请在下方上传文件或者手动输入后点击发送</div></div>`,
      };
      //清空之前的对话内容
      setHandleList(() => [systemCopyTip]);
      //行政知识局 需要增加数据正确性的提示
      if (currentTab.name === 'fact') {
        setTimeout(() => {
          let systemCopyTip2 = {
            type: 'systemCopy',
            data: `<div class="modeListBox"><div class="modeList autoWidth">需要保证数据的正确性。</div></div>`,
          };
          setHandleList((prev) => [...prev, systemCopyTip2]);
        }, 1000);
      }
    }
  }, [cognitionTypes, curTab]);

  //在文件解析后 增加一个操作表单
  const addForm = () => {
    let list = cloneDeep(curTabObj?.frontend_mete_data?.input || []);
    //必须有 添加 部分tab是没有操作表单
    if (list && list.length < 0) return;
    list.forEach((item: any) => {
      if (item.formItem === 'radio') {
        item.data = curTabObj?.second_class_list;
      }
    });

    let form = {
      type: 'form',
      data: list,
    };
    setHandleList((prev) => [...prev, form]);
    curForm.resetFields(); // 重置表单字段值
  };
  //解析组件的发送按钮回调
  const trainDocCb = (data: any) => {
    let trainSuccess = {
      type: 'trainSuccess',
      data: data,
    };
    setContent(data);
    setHandleList((prev) => [...prev, trainSuccess]);
    setHideBottomBtn(false); //显示底部训练按钮
    addForm();
  };

  //切换到输入形态
  const toggleInput = () => {
    updateState({
      curMode: 'input',
    });
  };
  //成功后的处理
  const submitSuccessHandle = (formData: any) => {
    //删除type=form
    setHandleList((prev: any) => {
      return prev.filter((item: any) => {
        return item.type !== 'form';
      });
    });

    let pText = '';
    formData.forEach((item: any) => {
      if (item.formItem === 'radio') {
        pText += `<p>${item.title}： ${item.value}</p>`;
      } else if (item.formItem === 'textarea') {
        pText += `<p>${item.title}： ${item.value}</p>`;
      } else if (item.formItem === 'switch') {
        pText += `<p>${item.title}： ${item.value ? '是' : '否'}</p>`;
      } else if (item.formItem === 'checkbox') {
        pText += `<p>${item.title}： ${item.value.join(',')}</p>`;
      }
    });
    let userInput = {
      type: 'userCommand',
      data: `<div class="modeListBox userIptBox"><div class="modeList">${pText}</div></div> `,
    };
    setHandleList((prev) => [...prev, userInput]);
    let systemCopyTip = {
      type: 'systemCopy',
      data: `<div class="modeListBox"><div class="modeList autoWidth">小麦已收到您的训练内容，开始计划训练</div></div>`,
    };
    setHandleList((prev) => [...prev, systemCopyTip]);
    setTrainingSuccess(true);
    props.createSuccess(curTabObj);
  };
  //提交失败
  const submitFailHandle = () => {
    setHideBottomBtn(true); //显示底部训练按钮
    //上传空文件提示
    let systemCopyTip = {
      type: 'systemCopy',
      data: `<div class="modeListBox"><div class="modeList autoWidth">您上传的文件为空文件，请重新上传</div></div>`,
    };
    setHandleList((prev) => [...prev, systemCopyTip]);
  };

  //好词好句提交
  const submitGoodSentence = async (formObj: any, formData: any) => {
    let newFormData: any = new FormData();
    //将formObj的参数添加到newFormData里
    Object.keys(formObj).forEach((key) => {
      newFormData.append(key, formObj[key]);
    });
    //类型是文字
    if (content.type === 'input') {
      newFormData.append('main_body', content.content);
    } else {
      //类型是文件
      newFormData.append('file', content?.file?.originFileObj, content?.file?.originFileObj?.name);
    }
    let res = await addGoodSentence(newFormData);
    if (res.code === 0) {
      submitSuccessHandle(formData);
    } else if (res.code === 20022) {
      submitFailHandle();
    } else {
      message.open({
        type: 'error',
        content: res.msg,
      });
    }
  };
  //好文收藏
  const submitGoodArticle = async (formObj: any, formData: any) => {
    let newFormData: any = new FormData();
    //将formObj的参数添加到newFormData里
    Object.keys(formObj).forEach((key) => {
      newFormData.append(key, formObj[key]);
    });
    //类型是文字
    if (content.type === 'input') {
      newFormData.append('main_body', content.content);
    } else {
      //类型是文件
      newFormData.append('file', content?.file?.originFileObj, content?.file?.originFileObj?.name);
    }
    let res = await addGoodArticle(newFormData);
    if (res.code === 0) {
      submitSuccessHandle(formData);
    } else if (res.code === 20022) {
      submitFailHandle();
    } else {
      message.open({
        type: 'error',
        content: res.msg,
      });
    }
  };
  //事实空间
  const submitFact = async (formObj: any, formData: any) => {
    let newFormData: any = new FormData();
    //将formObj的参数添加到newFormData里
    Object.keys(formObj).forEach((key) => {
      newFormData.append(key, formObj[key]);
    });
    //类型是文字
    if (content.type === 'input') {
      newFormData.append('main_body', content.content);
    } else {
      //类型是文件
      newFormData.append('file', content?.file?.originFileObj, content?.file?.originFileObj?.name);
    }
    let res = await addFact(newFormData);

    if (res.code === 0) {
      submitSuccessHandle(formData);
    } else if (res.code === 20022) {
      submitFailHandle();
    } else {
      message.open({
        type: 'error',
        content: res.msg,
      });
    }
  };
  //定期收集
  const submitCollection = async (formObj: any, formData: any) => {
    let newFormData: any = new FormData();
    //将formObj的参数添加到newFormData里
    Object.keys(formObj).forEach((key) => {
      newFormData.append(key, formObj[key]);
    });
    //类型是文字
    if (content.type === 'input') {
      newFormData.append('main_body', content.content);
    } else {
      //类型是文件
      newFormData.append('file', content?.file?.originFileObj, content?.file?.originFileObj?.name);
    }
    let res = await addCollection2(newFormData);
    if (res.code === 0) {
      submitSuccessHandle(formData);
    } else if (res.code === 20022) {
      submitFailHandle();
    } else {
      message.open({
        type: 'error',
        content: res.msg,
      });
    }
  };
  //参数转换
  const paramsConvert = (list: any) => {
    const transformedData: any = {};

    list.forEach((item: any) => {
      switch (item.formItem) {
        case 'radio':
          transformedData.tag = item.value;
          break;
        case 'textarea':
          transformedData.training_reason = item.value;
          break;
        case 'switch':
          transformedData.share_to_depart = item.value;
          break;
        case 'checkbox':
          transformedData.reference_content = item.value;
          break;
        // 如果还有其他类型的表单项，可以继续添加相应的处理逻辑
        default:
          break;
      }
    });

    return transformedData;
  };

  //开始训练
  const submitForm = () => {
    //查找当前表单数据
    let formData = handleList.filter((item: any) => item.type === 'form')[0];
    let fieldsValue = curForm.getFieldsValue();
    let reqCheck = 0;
    formData.data.forEach((item: any) => {
      if (item.required) {
        if (!fieldsValue[item.title]) {
          reqCheck++;
          message.open({
            type: 'warning',
            content: `${item.title}为必填项`,
          });
        } else if (Array.isArray(fieldsValue[item.title]) && fieldsValue[item.title].length === 0) {
          reqCheck++;
          message.open({
            type: 'warning',
            content: `${item.title}为必填项`,
          });
        }
      }
      item.value = fieldsValue[item.title] || '';
    });
    if (reqCheck > 0) return;
    let formObj = paramsConvert(formData.data);
    //好词好句
    if (curTab === 'good_sentence') {
      submitGoodSentence(formObj, formData.data);
    } else if (curTab === 'good_article') {
      //好文收藏
      submitGoodArticle(formObj, formData.data);
    } else if (curTab === 'fact') {
      //事实空间
      submitFact(formObj, formData.data);
    } else if (curTab === 'collection') {
      //定期收集
      submitCollection(formObj, formData.data);
    }
  };
  //再训练一次
  const againHandle = () => {
    setHideBottomBtn(true);
    setTrainingSuccess(false);
  };
  return (
    <div className="HandleModeWrap">
      <div className="HandleModeReturn" onClick={toggleInput}>
        <Button shape="circle" icon={<LeftOutlined />} />
      </div>
      <div className={`HandleModeMain ${hideBottomBtn ? 'miniHandleModeMain' : ''}`}>
        {handleList &&
          handleList.length > 0 &&
          handleList.map((item: any) => {
            if (item.type === 'systemCopy') {
              //系统文案
              return <div key={nanoid()} dangerouslySetInnerHTML={{ __html: item.data }}></div>;
            } else if (item.type === 'userCommand') {
              //用户输入的命令
              return <div key={nanoid()} dangerouslySetInnerHTML={{ __html: item.data }}></div>;
            } else if (item.type === 'trainSuccess') {
              return (
                <div className="modeListBox userIptBox" key={nanoid()}>
                  <div className="modeList fileInfoBox">
                    {item.data.type === 'file' && item?.data?.file?.originFileObj && (
                      <div className="fileInfo-hd">
                        {item?.data?.file?.originFileObj.accept === 'docx' ||
                        item?.data?.file?.originFileObj?.accept === 'doc' ? (
                          <FileWordOutlined />
                        ) : item?.data?.file?.originFileObj?.accept === 'txt' ? (
                          <FileTextOutlined />
                        ) : item?.data?.file?.originFileObj?.accept === 'pdf' ? (
                          <FilePdfOutlined />
                        ) : (
                          <FileUnknownOutlined />
                        )}
                      </div>
                    )}
                    <div className="fileInfo-bd">
                      {item.data.type === 'file' ? (
                        <span className="fileName">{item.data.name}</span>
                      ) : (
                        <div>{item.data.content}</div>
                      )}
                    </div>
                  </div>
                </div>
              );
            } else if (item.type === 'form') {
              return (
                <div className="modeListBox " key={nanoid()}>
                  <div className="modeList handleFormBox">
                    <Form layout="vertical" form={curForm} autoComplete="off">
                      {item.data &&
                        item.data.length > 0 &&
                        item.data.map((item2: any) => {
                          if (item2.formItem === 'radio') {
                            return (
                              <Form.Item
                                name={item2.title}
                                label={`请选择${item2.title}`}
                                key={nanoid()}
                                required={item2.required}
                              >
                                <Radio.Group optionType="button">
                                  {item2.data &&
                                    item2.data.length > 0 &&
                                    item2.data.map((item3: any) => {
                                      return (
                                        <Radio value={item3} key={nanoid()}>
                                          {item3}
                                        </Radio>
                                      );
                                    })}
                                </Radio.Group>
                              </Form.Item>
                            );
                          } else if (item2.formItem === 'checkbox') {
                            return (
                              <Form.Item
                                name={item2.title}
                                label={`请选择${item2.title}`}
                                key={nanoid()}
                                required={item2.required}
                              >
                                <Checkbox.Group>
                                  {item2.data &&
                                    item2.data.length > 0 &&
                                    item2.data.map((item3: any) => {
                                      return (
                                        <Checkbox key={nanoid()} value={item3}>
                                          {item3}
                                        </Checkbox>
                                      );
                                    })}
                                </Checkbox.Group>
                              </Form.Item>
                            );
                          } else if (item2.formItem === 'textarea') {
                            return (
                              <Form.Item
                                name={item2.title}
                                label={`请输入${item2.title}`}
                                key={nanoid()}
                              >
                                <TextArea autoSize={{ minRows: 4, maxRows: 4 }}></TextArea>
                              </Form.Item>
                            );
                          } else if (item2.formItem === 'switch') {
                            return (
                              <Form.Item
                                name={item2.title}
                                key={nanoid()}
                                required={item2.required}
                                style={{ marginTop: '20px' }}
                                label={item2.title}
                                labelAlign="right"
                                className="switchLable"
                                valuePropName="checked"
                              >
                                <Switch />
                              </Form.Item>
                            );
                          }
                          return <div key={nanoid()}></div>;
                        })}
                    </Form>
                  </div>
                </div>
              );
            } else {
              return <div key={nanoid()}></div>;
            }
          })}
      </div>
      <div
        className={`HandleModeBottom ${
          hideBottomBtn ? 'bigHandleModeBottom' : 'miniHandleModeBottom'
        }`}
      >
        {hideBottomBtn ? (
          <TrainDoc trainDocCb={trainDocCb}></TrainDoc>
        ) : !trainingSuccess ? (
          <Button type="primary" size="large" onClick={submitForm}>
            开始训练
          </Button>
        ) : (
          <Button type="primary" size="large" onClick={againHandle}>
            再训练一次
          </Button>
        )}
        {/* {!trainingSuccess ?(
          <Button type="primary" size="large" onClick={submitForm}>
          开始训练
        </Button>
        ):(
          <Button type="primary" size="large" onClick={againHandle}>
          再训练一次
        </Button>
        )} */}
      </div>
    </div>
  );
};

// export default HandleMode;
export default connect(({ spaceBot, spaceModel }) => ({ spaceBot, spaceModel }))(HandleMode);
